package com.kh.statistics.video.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kh.statistics.video.config.RedisService;
import com.kh.statistics.video.constant.AccountsConstant;
import com.kh.statistics.video.entity.VideoAccountsLogin;
import com.kh.statistics.video.service.AccountLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class AccountLoginServiceImpl implements AccountLoginService {


    @Autowired
    private RedisService redisService;

    @Override
    public void saveLoginLog(VideoAccountsLogin videoAccountsLogin) {
        redisService.setKey(String.format(AccountsConstant.VIDEO_ACCOUNTS_LOGIN, videoAccountsLogin.getId() + "_" + videoAccountsLogin.getPlatform()),
                JSON.toJSONString(videoAccountsLogin));
    }

    @Override
    public List<VideoAccountsLogin> searchAll() {
        Set<String> keys = redisService.getAll(String.format(AccountsConstant.VIDEO_ACCOUNTS_LOGIN, "*"));
        List<String> list = redisService.multiGet(keys);
        return list.stream().map(item -> JSONObject.parseObject(item, VideoAccountsLogin.class)).collect(Collectors.toList());
    }

    @Override
    public boolean deleteById(String id) {
        Set<String> keys = redisService.getAll(String.format(AccountsConstant.VIDEO_ACCOUNTS_LOGIN, id + "_*"));
        redisService.deleteKey(keys);
        return true;
    }

    @Override
    public void loginExpand(VideoAccountsLogin videoAccountsLogin) {
        redisService.setKey(String.format(AccountsConstant.VIDEO_ACCOUNTS_LOGIN, videoAccountsLogin.getId() + "_" +
                        videoAccountsLogin.getPlatform() + "_" + videoAccountsLogin.getClient()),
                JSON.toJSONString(videoAccountsLogin));
    }
}
